/* eslint-disable no-return-assign */
/* eslint-disable no-unused-vars */
/* eslint-disable prefer-const */
<template>
  <page-header-wrapper>
    <div>
      <div class="scroll">
        <a-row :gutter="3">
          <a-col :span="treespan">
            <div class="scroll-interior">
              <s-tree
                :dataSource="orgTree"
                :search="false"
                @click="handleClick"
                :selectKey="defaultSelectKey"
              >
              </s-tree>
            </div>
          </a-col>
          

          <a-col :span="8">
            <a-select 
              v-model="selectValue" 
              placeholder="请选择项目"
              show-search
              @change="onChange"
              @search="onSearch"
              @focus="handleFocus"
              :options="options"
              style="width: 393px;margin-left:0px"
              size="large"
            >
            </a-select>
            <a-card title="班组及工人入场信息登记" :bordered="false" class="acard">
              <a-list class="ban">
                <a-list-item>
                  <a size="large" @click="showQRcode" class="register">登记</a>
                  <span> (可点击进入扫码登记)</span>
                </a-list-item>
                <a-list-item>
                  <a size="large" @click="addteam" class="register">新增</a>
                  <span> (可点击新增自定义班组)</span>
                </a-list-item>
              </a-list>
              <a-modal
                v-model="visible"
                title="信息登记"
                ok-text="确认"
                cancel-text="取消"
                @ok="qrcodemodel"
                width="40%"
              >
                <div class="erweima" id="qrcode" ref="qrcode"></div>
              </a-modal>
              
              <a-modal
                v-model="freevisible"
                title="新增自定义班组"
                ok-text="确认"
                cancel-text="取消"
                @ok="freevisibleOk"
                @cancel="freevisibleClose"
                width="40%"
              >
                <a-form-model
                  ref="addname"
                  :model="addname"
                  :label-col="{span: 5}"
                  :wrapper-col="{span: 16}"
                  :rules="rules"
                >
                  <a-form-model-item label="班组名称" prop="team_name">
                    <a-input v-model="addname.team_name"></a-input>
                  </a-form-model-item>
                </a-form-model>
              </a-modal>
              <a-modal
                v-model="more_ok"
                title="提示"
                ok-text="确认"
                cancel-text="取消"
                @ok="addOk"
              >
                <p style="color:red;display:flex;justify-content:center ;">请再次确认是否需要取消，点击确认后不可删除班组！</p>
              </a-modal>
            </a-card>
          </a-col>
          <a-col :span="8">
            <a-select
              v-model="selectValue1" 
              placeholder="请选择班组"
              :options="options1"
              @focus="handleFocus1"
              @change="toChange"
              style="width: 314px;margin-left:0px"
              size="large"
            >
            </a-select>
            <a-button size="large" @click="toSearch" style="margin-left:10px">搜索</a-button>
            <a-card title="工人入场信息记录" :bordered="false" class="card">
              <a-modal
                v-model="outvisible"
                title="输出信息登记"
                ok-text="确认"
                cancel-text="取消"
                @ok="outqrcodemodel"
                width="50%"
              >
                <div id="screenViewBox">
                  <div class="picture">
                    <div id="qrCode" ref="qrCode"></div>
                    <div class="content">
                      <span style="font-size:22px;font-weight:650;">工人入场登记记录汇总</span>
                      <span style="font-size:18px;font-weight:650;">工程名称：{{ projectname }}</span>
                      <span style="font-size:18px;font-weight:650;">班组名称：{{ teamname }}</span>
                      <span style="font-size:18px;font-weight:650;">记录数：{{ allmenber }}</span>
                      <span style="font-size:18px;font-weight:650;">汇总日期：{{ gathertime }}</span>
                    </div>
                  </div>
                </div>
                <a-button class="savePoster" type="primary" @click="savePoster">保存为图片</a-button>
              </a-modal>
              
              <!-- 退场 -->
              <a-modal
                v-model="exitvisible"
                title="退场"
                ok-text="确认"
                cancel-text="取消"
                @ok="exitok"
                width="50%"
              >
                <span> 请确认退场班组是否为{{ projectname }}:{{ teamname }}?</span>
              </a-modal>
              <!-- 恢复 -->
              <a-modal
                v-model="recovervisible"
                title="退场"
                ok-text="确认"
                cancel-text="取消"
                @ok="recoverok"
                width="50%"
              >
                <span> 请确认是否恢复{{ projectname }}:{{ teamname }}?</span>
              </a-modal>

              <div v-if="allmenber > 0" class="outdata">
                <a-list>
                  <a-list-item>
                    {{ projectname }} : {{ teamname }}
                    <a class="butn" v-show="createPassShow" size="large" @click="outshowQRcode">
                      详情
                    </a>
                    <span> (点击查看详情)</span>
                  </a-list-item>
                  <a-list-item>
                    {{ projectname }} : {{ teamname }}
                    <a class="butn1" v-show="createPassShow" size="large" @click="exit_team">
                      退场
                    </a>
                    <span> (点击一键退场)</span>
                  </a-list-item>
                  <a-list-item>
                    {{ projectname }} : {{ teamname }}
                    <a class="butn1" v-show="createPassShow" size="large" @click=" recover_team">
                      恢复
                    </a>
                    <span> (点击一恢复退场)</span>
                  </a-list-item>
                </a-list>
                <!-- <a-list>
                  <div class="listwhere">
                    <span style="font-size:20px;margin-left:130px">项目名称</span>
                    <span style="font-size:20px;margin-left:130px">班组名称</span>
                    <span style="font-size:20px;margin-left:80px">二维码</span>
                  </div>
                  <template v-for="(item,index) in allmenber">
                    <a-list-item :key="index" style="font-size:16px">
                      {{ index+1 }} &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                      &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                      &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                      {{ projectname }} &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                      &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                      &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{{ teamname }}
                    </a-list-item>
                  </template>
                </a-list> -->
              </div>
              <div v-else>
                <template>
                  <Empty class="empty" description="该班组没有人员登记!"></Empty>
                </template>
              </div> 
            </a-card>
          </a-col>
        </a-row>
      </div>
    </div>
  </page-header-wrapper>
</template>

<script>
import STree from '@/components/Tree/Tree'
import QRCode from 'qrcodejs2'
import { showprojectname,queryproject,showteam,sideborder,querydrop,qraddteam,teamexit,teamrecover} from '@/api/programDiscuss'
import { Empty } from 'ant-design-vue'
import { mapState } from 'vuex'
import html2canvas from 'html2canvas'

const delay = (function () {
 let timer = 0
 return function (callback, ms) {
  clearTimeout(timer)
  timer = setTimeout(callback, ms)
 }
})
export default {
  components: { QRCode,STree,Empty },
  data() {
    return {
    gathertime:'',//汇总日期
    createPassShow: true,
    visible:false,
    freevisible:false,
    outvisible:false,
    exitvisible:false,//退场
    recovervisible:false,//恢复
	  search:'',
	  orgTree: [],//侧边栏列表
	  treespan: 3,
	  tablespan: 21,
    allmenber:'',
    defaultSelectKey:[1],//默认选中的高亮
	  openKeys: [1], // 默认打开树状列表的key值
	  projectTypeId: '',
    teamname:'',
    uid:'',
    projectname:'',
    options: [],
    value: '',
    selectValue:undefined,
    selectValue1:undefined,
    options1:[],
    rules: {
      team_name: [
        { required: true, message: '内容不可为空', trigger: 'blur' }
      ]
    },
    addname:{},
    team_name:'',
    // popvisible: false,
    // condition: true
    more_ok:false //再次确认新增班组
    }
  },
  computed: {
    ...mapState({
      roleId: state => state.user.info.roleId
    })
  },
  watch: {
    search: function (newVal, oldVal) {
      delay(() => {
        this.onSearch(newVal)
      }, 1000)
    },
  },
  created () {
  this.getMenuInfo()
},
  mounted () {
  },
  methods: {
    savePoster(){
      const that = this
      //打开loading
      that.savePosterLoading = true
      //生成图片之前，需先将整体的滚动条隐藏掉，否则生成出来的照片会偏移
      document.getElementById('app').style.overflowY = 'hidden'
       //两个参数：所需要截图的元素id，截图后要执行的函数， canvas为截图后返回的最后一个canvas
       var shareContent = document.getElementById('screenViewBox')
      var width = shareContent.offsetWidth
      var height = shareContent.offsetHeight
      var canvas = document.createElement('canvas')
      var scale = 5 //这里为了下载出更清晰的图片，值越大越清晰

      canvas.width = width * scale
      canvas.height = height * scale
      canvas.getContext('2d').scale(scale, scale)

      var opts = {
          scale: 1,//不管上面的scale是多少倍，这里只能取1，否则会显示不完全
          canvas: canvas,
          logging: true,
          width: width,
          height: height
      }
      const downloadName = '下载的图片名称'
      // html2canvas(shareContent,opts).then(
      //   function(canvas) {
      //   //这个方式是直接将canvas保存为图片的，具体参数可自行查看源码
      //    var img = Canvas2Image.saveAsImage(canvas, canvas.width, canvas.height,'PNG',downloadName)
      //   //这个方式只是提供展示图片的功能，暂时没有用到
      //   var img = Canvas2Image.convertToPNG(canvas, canvas.width, canvas.height,'PNG')
      //    document.body.appendChild(img)

      //    //生成图片之前，需先将整体的滚动恢复为之前的状态
      //    document.getElementById('app').style.overflowY = 'scroll'
      //   //关闭loading
      //    that.savePosterLoading = false
      //   },

      //     )
      html2canvas(this.$refs.shareContent, { useCORS: true, logging: true }).then((canvas) => {
        const dataURL = canvas.toDataURL('image/png')
        this.download(dataURL, opts)
      })
    },


    qrcode (arid) { // https://blog.csdn.net/qq_42866164/article/details/104960777根据这个教程写的
      var arid = this.treekey
      const text = `https://www.zsjx.fit/User?judgeinout=${arid}` // 生成二维码的链接
      const qrcode = new QRCode('qrcode', {
        width: 192, // 二维码宽度，单位像素
        height: 192, // 二维码高度，单位像素
        text: text, // 生成二维码的链接
        render: 'canvas'
      })
      // qrcode.toDataURL(text, (url) => {
      //     this.$refs.qrcode.src = url
      //   })
      return qrcode
    },
    showQRcode () {
      this.visible = true
      this.$nextTick(function () {
        this.$refs.qrcode.innerHTML = ''
        this.qrcode()
      })
    },
    qrcodemodel () {
      this.visible = false
    },
    //班组新增
    addteam () {
      this.freevisible = true
    },
    freevisibleOk () {
      this.$refs.addname.validate(valid => {
        if (!valid) {
          return false
        } else {
          this.more_ok = true
        }
      })
    },
    freevisibleClose (addname) {
      this.freevisible = false
      this.addname.team_name = ''
      // this.form = {}
      if(this.$refs.addname !== undefined) {
      this.$refs.addname.clearValidate()
      }
    },
    //再次确认新增班组
    addOk () {
            // this.confirmLoading = true
            var newteam = new FormData()
            newteam.append('team-add', this.addname.team_name)
            qraddteam(newteam).then(res => {
              if (res.message === 'success') {
                      this.$message.success('添加成功')
                      this.freevisible = false
                     if (this.$refs.addname !== undefined) {
                        this.$refs.addname.clearValidate()
                        }
                      this.getMenuInfo()
                    } else {
                      alert(res.message)
                    }
                  })
          this.more_ok = false
    },

    //输出二维码
    outqrcode (uid) {
      var uid = this.treekey
      var fid = this.openKeys[0]
      console.log(this.treekey)
      const text = `https://www.zsjx.fit/User?team=${uid}&projectname=${fid}`
      var outqrcode = new QRCode('qrCode',{
        width: 192, // 二维码宽度，单位像素
        height: 192, // 二维码高度，单位像素
        text: text, // 生成二维码的链接
        render: 'canvas'
      })
      console.log(uid)
      return outqrcode
    },
    outshowQRcode () {
      this.outvisible = true
      this.$nextTick(function () {
        this.$refs.qrCode.innerHTML = ''
        this.outqrcode()
      })
    },

    //一键退场
    exit_team () {
      this.exitvisible = true 
    },
    exitok () {
      this.exitvisible = false
      var newexit = new FormData()
            newexit.append('team_key', this.treekey)
            newexit.append('project_name', this.openKeys[0])
            teamexit(newexit).then(res => {

              })
    },
        //恢复退场
    recover_team () {
      this.recovervisible = true 
    },
    recoverok () {
      this.recovervisible = false
      var newexit = new FormData()
            newexit.append('team_key', this.treekey)
            newexit.append('project_name', this.openKeys[0])
            teamrecover(newexit).then(res => {

              })
    },

    outqrcodemodel () {
      this.outvisible = false
    },

	getMenuInfo () {
      showprojectname().then(res => {
        this.orgTree = res.result
        this.treekey = res.result[0].children[0].key.split('-')[3]
        console.log(this.treekey)
        this.defaultSelectKey[0] = this.orgTree[0].children[0].key.split('-')[3] //返回班组的key 这项 可打开默认得班组页面
        this.openKeys[0] = this.orgTree[0].key//项目 这项
        // this.projectTypeId = this.orgTree[0].children[0].key.split('-')[3] //这项 
        this.getTableData()
    })
	},
	handleClick (e) {
      this.treekey = e.key.split('-')[3]
    console.log(e.key.split('-')[3])
      this.defaultSelectKey[0] = e.key.split('-')[3]
      // this.projectTypeId = e.key //班组
      this.openKeys[0] = e.keyPath[1].split('-')[0]//项目
      console.log(this.openKeys[0])
      this.getTableData()
    },
    getTableData () {
      this.loading = true
      if (this.roleId !== 'admin') {
        this.createPassShow = false
      }
      var formdata = new FormData()
      formdata.append('team_key', this.treekey)
      formdata.append('project_name', this.openKeys[0])
      showteam(formdata).then(res => {
          this.allmenber = res.result[1].allmenber
          this.treekey = res.result[1].children.key.split('-')[3]
          this.teamname = res.result[1].children.title
          this.projectname = res.result[1].title
          if( this.allmenber > 0 )
          {
            this.menber = res.result[2]
            this.last = this.menber[this.menber.length-1]
            this.gathertime = this.last.indate //汇总日期
            console.log(this.gathertime)
            // console.log(this.menber[this.menber.length-1])
          }
          

          // Object.values( this.menber )
          // console.log(Object.values( this.menber ))

      })
    },
      
    onChange(value){
      this.selectValue = value
      for(var i=0;i<this.options.length;i++){
        var oneoptions = this.options[i]
        if( value===oneoptions.value) {
          this.options1 
        }
      }
    },
    toChange(value) {
        this.selectValue1 = value
    },
    handleFocus() {
      queryproject().then(res => {
        this.options = res.result
      })
    },
    handleFocus1() {
      querydrop().then(res => {
        this.options1 = res.result
      })
    },

    onSearch(value){
      this.onChange(value)
      var searchmes = new FormData()
      searchmes.append('query_project_name', this.selectValue)
      this.loading = true
      queryproject(searchmes).then(res => {
        this.options = res.result
      })
    },
    toSearch () {
    var searchsth = new FormData()
    searchsth.append('border_project_name',this.selectValue)
    searchsth.append('border_team_name',this.selectValue1)
    sideborder(searchsth).then(res => {
      this.treekey = res.result.team_key.split('-')[1]
      this.openKeys[0] = res.result.project_key
    console.log(this.openKeys[0])
    this.getTableData()
    })
    }
  }
}
</script>

<style>
.erweima{
  display:flex;
  justify-content: center;
}
.scroll{
    width: 100%;
    display:inline-block;
    /* font-size: 0; */
}
.scroll-interior{
    overflow-y:scroll;
    overflow-x:hidden;
    width: 140px ;
    height: 350px;
}
.outdata {
  margin-left:30px;
  margin-top: 20px;
}
.ant-list {
  font-size: 15px;
}
.ban {
  margin-left:50px;
  margin-top: 43px;
}
.butn {
  margin-left:30px;
}
.butn1 {
  margin-left:30px;
}
.register {
  margin-left:30px;
}
.empty {
  margin-top:45px;
}
.listwhere {
  margin-top:15px;
  font-size:20px;
  color:rgb(97, 95, 95)
}
.card {
  height: 300px;
  margin-top:10px;
}
.acard {
  height: 300px;
  margin-top:10px;
}
.picture {
  height: 200px;
  display: flex;
  align-items:flex-start;
}
.content {
  height: 192px;
  flex-direction:column;
  justify-content:space-between;
  display: flex;
  flex-wrap:wrap;
  margin-left: 20px;
}
</style>